import { vh, vw } from "@/common/dimensions";
import globalStyles from "@/common/styles/globalStyles";
import LazyImage from "@/components/LazyImage";
import NavHeader from "@/components/NavHeader";
import {
    activeCategoryIdAtom,
    categoryItemType,
    categoryListAtom,
    SceneItemType,
    stickerDataAtom,
} from "@/store/home";
import { LinearGradient } from "expo-linear-gradient";
import { useAtom } from "jotai";
import React, { useEffect, useMemo, useState } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
import FooterButton from "./FooterButton";
import { beforeCreateTask } from "@/utils/createTask";
import { userImgParamsAtom, userInfoAtom } from "@/store/user";
import Toast from "react-native-toast-message";
import { createStickerServer } from "@/servers/app-servers";
import MonitorCode from "@/utils/MonitorCode";
import GlobalModal, { ModalPropsType } from "@/components/GlobalModal";
import { router } from "expo-router";
import { useResultShow } from "@/hooks/useResultShow";
import { useUpdateUserInfo } from "@/hooks/useUpdateUserInfo";

export default function Sticker(props: { id: number }) {
    let { id } = props;
    // 首页频道列表
    const [categoryList] = useAtom(categoryListAtom);
    // 当前选中的频道Id
    const [activeCategoryId] = useAtom(activeCategoryIdAtom);
    // 当前模板的标题
    const [navTitle, setNavTitle] = useState<string>("");
    // 当前模板的展示
    const [coverImageList, setCoverImageList] = useState<{ path: string }[]>([]);
    // stickerData
    const [stickerData, setStickerData] = useAtom(stickerDataAtom)
    // 当前 decorateId
    const [decorateId, setDecorateId] = useState(0)
    // 用户信息
    const [userInfo] = useAtom(userInfoAtom)
    // 模板是否为收费模板
    const [chargeType, setChargeType] = useState('')
    // 选择的颜色参数
    const [colorParams, SetColorParams] = useState('')
    // flowid
    const [flowId , setFlowId] = useState("")
    // 用户图片数据
    const [ ImgParam ] = useAtom(userImgParamsAtom)
    // 通用弹框是否显示
    const [showModal, setShowModal] = useState(false);
    // 当前decro
    const [ decroStr , setDecroStr ] = useState('')
    // 自定义hook 获取 resultShow
    const { getResultShow } = useResultShow()
    // 自定义hook 更新userInfo
    const { updateUserInfo } = useUpdateUserInfo()

    // 关闭弹框
    const hideModal = () =>{
        setShowModal(false)
    }

    // 去作品页
    const gotoWord = () => {
        hideModal()
        router.navigate('/(tabs)/work')
    }


    // 默认弹框数据
    const [modalProps , setModalProps] = useState<ModalPropsType>({
        title: "温馨提示",
        content: `提示内容`,
        cancelText: "取消",
        confirmText: "确定",
        onCancel: hideModal,
        onConfirm: hideModal,
        hideModal
    })


    useEffect(() => {
        const foundCategory = categoryList.find((item: categoryItemType) => item.id === activeCategoryId)?.sceneList.find((item: SceneItemType) => item.id === id) as SceneItemType;
        const { charge_type, json_content: { cn: { title }, cover_image_list, app_flow_id , flow_param: { decorate_id } } } = foundCategory;
        setFlowId(app_flow_id)
        setChargeType(charge_type)
        setDecorateId(Number(decorate_id))
        setNavTitle(title);
        setCoverImageList(cover_image_list);
    }, [id, categoryList, activeCategoryId]);

    const stickerDataByDecorateId = useMemo(() => {
        if ("decorateList" in stickerData) {
            return stickerData.decorateList.find(item => item.id === decorateId)
        }
    }, [decorateId, stickerData])

    const stickerDataColorList = useMemo(() => {
        if ("colorList" in stickerData) {
            SetColorParams(stickerData.colorList[0].item)
            return stickerData.colorList
        }
    }, [stickerData])

    const onPressCreate = async () => {
        const res = beforeCreateTask(userInfo.is_pro, chargeType)
        if (!res) {
            Toast.show({
                type:"error",
                text1:"付费模板，请开通会员再尝试~"
            })
            return
        }
        let decro = "";
        stickerDataByDecorateId?.json_data.cn.showData.map(item => item.option.dataList[item.selectVal]).forEach(item => item && (decro = `${decro},${item}`))
        decro = decro.slice(1)
        setDecroStr(decro)
        const option = {
            app_show_id:id,
            flow_id:flowId,
            original_img_id:ImgParam.id,
            decro,
            color:colorParams
        }
        await createSticker(option)
    }

    const againCreate = async () => {
        const option = {
            app_show_id:id,
            flow_id:flowId,
            original_img_id:ImgParam.id,
            decro:decroStr,
            color:colorParams,
            duplicate_check: 2,
        }
        await createSticker(option)
        await updateUserInfo()
    }

    const createSticker = async(data:any) =>{
        const res = await createStickerServer(data)
        const { code , msg } = res
        let modalProps;
        switch (code) {
            case 0:
                await getResultShow()
                await updateUserInfo()
                modalProps = MonitorCode.encounter(userInfo, hideModal ,gotoWord );
                break;
            case 1000:
                modalProps = MonitorCode.encounter1000(hideModal , againCreate);
                break;
            case 1001:
                modalProps = MonitorCode.encounter1001(hideModal);
                break;
        }
        if(modalProps){
            setModalProps(modalProps)
            setShowModal(true)
        }
    }

    const changeDecorate = (data: { selectVal: number; name: string }, index: number) => {
        setStickerData((prevStickerData) => {
            // 复制当前的 stickerData
            const newStickerData = { ...prevStickerData };
            // 找到对应的 decorateList 项
            const decorateItem = newStickerData.decorateList?.find(item => item.id === decorateId);
            if (decorateItem) {
                // 找到需要更新的 showData 项目
                const showDataItem = decorateItem.json_data.cn.showData.find(showItem => showItem.name === data.name);
                if (showDataItem) {
                    // 更新选中的值
                    showDataItem.selectVal = index;
                }
            }
            // 返回更新后的 stickerData
            return newStickerData;
        });
    }

    return (
        <View>
            <LinearGradient
                colors={["#fdfaf2", "#fff"]}
                style={styles.container}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
            >
                <NavHeader navTitle={navTitle} />
                <View
                    style={[
                        globalStyles.rowLine,
                        globalStyles.jcSB,
                        styles.showImage,
                    ]}
                >
                    {coverImageList.map((item) => (
                        <LazyImage
                            uri={item.path}
                            key={item.path}
                            style={[coverImageList.length ===9  ? styles.imageMode3 : styles.imageMode2]}
                            defaultSource={require("@/assets/common/perch.png")}
                        />
                    ))}
                </View>
            </LinearGradient>
            <View style={{ backgroundColor: "#fff", paddingHorizontal: 4 * vw }}>
                <Text style={styles.decorateTitle}>选择配饰</Text>
                {
                    stickerDataByDecorateId?.json_data.cn.showData.map(item => (
                        <View key={item.name} style={[globalStyles.rowLine, globalStyles.aiCenter, { marginBottom: 12 }]}>
                            {/* 表头 */}
                            <Text style={styles.decorateLabel}>{item.name}：</Text>
                            {/* 选项 */}
                            <View style={[globalStyles.rowLine]}>
                                {
                                    item.option.list.map((l, index) => (
                                        <TouchableOpacity key={l} onPress={() => changeDecorate(item, index)}>
                                            <Text style={[styles.otherSelect, item.selectVal === index && styles.active]} >{l}</Text>
                                        </TouchableOpacity>
                                    ))
                                }
                            </View>
                        </View>
                    ))
                }
                <Text style={styles.decorateTitle}>选择色调</Text>
                <View style={[globalStyles.rowLine, globalStyles.jcSE]}>
                    {
                        stickerDataColorList?.map(item => (
                            <TouchableOpacity key={item.item} onPress={()=> SetColorParams(item.item)} >
                                <View
                                    style={[{ backgroundColor: item.color }, styles.colorItem, item.item === colorParams && styles.activeColor]}
                                ></View>
                            </TouchableOpacity>
                        ))
                    }
                </View>
                <FooterButton onPressCreate={onPressCreate} />
            </View>
            <Toast />
            <GlobalModal
				visible={showModal}
				modalProps={modalProps}
			/>
        </View>
    );
}
const styles = StyleSheet.create({
    container: {
        paddingHorizontal: 4 * vw,
        paddingTop: 10 * vw,
    },
    showImage: {
        flexWrap: "wrap",
        marginVertical: 6 * vw
    },
    imageMode2: {
        width: 44 * vw,
        height: 44 * vw,
        borderRadius: 8,
        marginBottom: 2 * vw,
    },
    imageMode3: {
        width: 30 * vw,
        height: 30 * vw,
        borderRadius: 8,
        marginBottom: 1 * vw,
    },
    decorateTitle: {
        fontSize: 16,
        color: "#000",
        fontWeight: "600",
        marginBottom: 4 * vw
    },
    decorateLabel: {
        fontSize: 14,
        color: "#000",
        fontWeight: "500",
        marginRight: 12
    },
    otherSelect: {
        fontSize: 12,
        paddingVertical: 6,
        paddingHorizontal: 10,
        backgroundColor: "#f4f4f4",
        borderRadius: 6,
        marginRight: 16
    },
    active: {
        backgroundColor: "#fff7c0",
        color: "#fd9c35"
    },
    colorItem: {
        width: 40,
        height: 40,
        borderRadius: 20
    },
    activeColor: {
        borderWidth: 1,
        borderColor: "#000"
    }
});
